<template>
  <div>
    <div class="top" v-loading="loading">
      <el-page-header @back="goBack"></el-page-header>
      <div class="topBar" style="margin-top: 5px">
        <div class="left">
          <p style="font-size: 18px;margin-bottom: 5px">{{ cateTypeInfo.templateName }}</p>
          <p style="color: #595959">问题项总数：<span style="margin-right: 40px">{{ cateTypeInfo.totalProblem }}</span>
            总分：<span style="margin-right: 10px">{{
                cateTypeInfo.totalScore || "--"
              }}</span>
            | 问题项分数之和</p>
        </div>
        <div class="right">
          <el-button style="width: 120px;background-color:#303e9d;color: #eeeeee" @click="_setting" size="small"><i
              class="el-icon-edit"
              style="margin-right: 5px"></i>模板设置
          </el-button>
        </div>
      </div>
      <div class="centerBar">
        <div class="left">
          <div style="display: flex;justify-content: space-between;align-items: center">
            <p style="font-size: 16px;">巡查大类</p>
            <el-button @click="addCate" style="border: 1px solid #eee" size="small"><i class="el-icon-plus"
                                                                                       style="margin-right: 10px"></i>添加大类
            </el-button>
          </div>
          <div>
            <span style="font-size: 12px;color: #919398;">普通类</span>
            <div
                class="box-card"
                v-for="(item,index) in cateTypeList.filter(i => i.largeType ==1)"
                :key="item.largeId"
                :class="{ 'active-border': activeCard === item.largeId }"
                @click="activeCard = item.largeId; scrollToTarget(index)"
            >
              <div style="display: flex">
                <p><img src="@/assets/img/chugui.svg" alt="" style="width: 24px;"></p>
                <p style="margin-left: 5px;font-size: 16px">{{ item.largeName }}</p>
              </div>
              <div>{{ item.largeScore }} 分</div>
              <div class="button-group">
                <el-link @click.stop="editCateName(item.largeId)"><i class="el-icon-edit"></i></el-link>
                <el-link @click.stop="deleteCateName(item.largeId)"><i class="el-icon-delete"></i></el-link>
              </div>
            </div>
            <img v-if="!cateTypeList.some(i => i.largeType == 1)" src="@/assets/img/nodata.svg" alt=""
                 style="width: 100px;display: block;margin-top: 15px">
          </div>

          <!--                    <div style="margin-top: 20px">-->
          <!--                      <span style="font-size: 12px;color: #919398;">额外类（分数不计入总分）</span>-->
          <!--                      <div-->
          <!--                          class="box-card"-->
          <!--                          v-for="item in cateTypeList.filter(i => i.largeType ==2)"-->
          <!--                          :key="item.largeId"-->
          <!--                          :class="{ 'active-border': activeCard === item.largeId }"-->
          <!--                          @click="activeCard = item.largeId"-->
          <!--                      >-->
          <!--                        <div style="display: flex">-->
          <!--                          <p><img src="@/assets/img/chugui.svg" alt="" style="width: 24px;"></p>-->
          <!--                          <p style="margin-left: 5px;font-size: 16px">{{ item.largeName }}</p>-->
          <!--                        </div>-->
          <!--                        <div class="button-group">-->
          <!--                          <el-link @click.stop="editCateName(item.largeId)"><i class="el-icon-edit"></i></el-link>-->
          <!--                          <el-link @click.stop="deleteCateName(item.largeId)"><i class="el-icon-delete"></i></el-link>-->
          <!--                        </div>-->
          <!--                      </div>-->
          <!--                      <img v-if="!cateTypeList.some(i => i.largeType == 2)" src="@/assets/img/nodata.svg" alt=""-->
          <!--                           style="width: 100px;display: block;margin-top: 15px">-->
          <!--                    </div>-->

        </div>
        <div class="right">
          <div class="selectBar" style="display: flex;justify-content: space-between">
            <div>
              <el-button-group>
                <el-button style="border: 1px solid #eee" size="small" :disabled="true">按巡查项</el-button>
                <el-button style="border: 1px solid #eee" size="small">按巡查问题</el-button>
              </el-button-group>
              <el-button style="border: 1px solid #eee;width: 100px;margin-left: 15px" size="small"
                         @click="collapse=true"><i class="el-icon-caret-bottom
"></i>展开
              </el-button>
              <el-button style="border: 1px solid #eee;width: 100px;" size="small" @click="collapse=false"><i
                  class="el-icon-caret-top"></i>折叠
              </el-button>
            </div>

            <div>
              <el-input v-model="searchFn" placeholder="请输入问题名称搜索" size="small" suffix-icon="el-icon-search"
                        @input="searchM"></el-input>
            </div>
          </div>
          <div class="contentBar">
            <div class="normal" v-for="(item,index) in cateTypeList" :key="index">
              <p class="target" :data-id="index"></p>
              <div style="display: flex;justify-content: space-between;align-items: center">
                <p style="margin-top: 15px;font-size: 18px;font-weight: 500">
                  {{ item.largeName }}（{{ item.largeScore }}分）<span
                    style="color: #919398;font-size: 15px">共{{ item.largeProblemNum }}个问题</span>
                </p>
                <el-button style="background-color:#303e9d;color: #fff" size="small" @click="addInspection(item)"><i
                    class="el-icon-plus"
                    style="margin-right: 10px"></i>添加巡查项
                </el-button>
              </div>
              <div>
                <div class="typePic" v-for="b in item.termVoList">
                  <div class="tableCard">
                    <div class="a">
                      <p><i class="el-icon-arrow-down" v-if="collapse"></i><i class="el-icon-arrow-up"
                                                                              v-if="!collapse"></i><span>{{
                          b.termName
                        }}({{ b.termScore }}.0)</span>
                        <span style="margin-left: 20px">共{{ b.termProblemNum }}个问题</span>
                      </p>
                      <p>
                        <el-button style="border: 1px solid #eee" size="small" @click="addPro(b.termId)"><i
                            class="el-icon-plus"
                            style="margin-right: 10px"></i>添加问题
                        </el-button>
                        <i class="el-icon-edit" style="margin-left: 10px;font-size: 18px"
                           @click="editPatrolSetting(b)"></i>
                        <i class="el-icon-delete" style="margin-left: 10px;font-size: 18px"
                           @click="deletePatorlInfo(b.termId)"></i>
                      </p>
                    </div>
                    <el-table :data="b.list"
                              v-if="collapse"
                              @selection-change="handleSelectionChange"
                    >
                      <el-table-column
                          type="selection"
                          width="55">
                      </el-table-column>
                      <el-table-column prop="problemName" label="问题项名称" width="300px"></el-table-column>
                      <el-table-column prop="problemScore" label="分数"></el-table-column>
                      <el-table-column prop="problemType" label="问题类型">
                        <template v-slot:default="scope">
                          <span v-if="scope.row.problemType=='1'">一般问题</span>
                          <span v-if="scope.row.problemType=='2'">重要问题</span>
                          <span v-if="scope.row.problemType=='3'">红线问题</span>
                        </template>
                      </el-table-column>
                      <el-table-column label="巡查场景">
                        <template v-slot:default="scope">
                          <div class="scopePic">一般场景</div>
                        </template>
                      </el-table-column>
                      <el-table-column prop="" label="操作">
                        <template v-slot:default="scope">
                          <i class="el-icon-edit" style="margin-left: 10px;font-size: 18px"
                             @click="editPro(scope.row)"></i>
                          <i class="el-icon-delete" style="margin-left: 10px;font-size: 18px"
                             @click="deletePro(scope.row.problemId)" v-if="b.list.length!=1"></i>
                        </template>
                      </el-table-column>
                    </el-table>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <!--    <div class="bottom">-->
    <!--      <el-button style="width: 120px;background-color:#303e9d;color: #eeeeee;margin-top: 10px;">完 成</el-button>-->
    <!--    </div>-->

    <div class="add">
      <el-dialog :visible.sync="addCategory" :title="categoryTittle" width="30%">
        <p style="margin-bottom: 10px">类型 <span style="color: #ce0e0f">*</span></p>
        <el-radio-group v-model="largeType" autofocus @input="changeLargeType">
          <el-radio :label="1">普通类</el-radio>
        </el-radio-group>
        <span v-if="largeType=='2'" style="display: block;margin-top: 5px;color: #919398">额外类的分数不计入模板总分，但巡查时问题得分计入巡查总得分。一般用于额外加减分处理</span>
        <p style="margin: 10px 0">名称 <span style="color: #ce0e0f">*</span></p>
        <el-input size="small" placeholder="请输入添加的大类名称" v-model="largeName"></el-input>
        <span slot="footer">
   <el-button style="background-color:#303e9d;color: #eeeeee" @click="comfirmCate">确 定</el-button>
     <el-button style="border: 1px solid #eee" @click="addCategory=false">取 消</el-button>
        </span>
      </el-dialog>
    </div>
    <el-dialog :visible.sync="CateName" title="修改大类名称" width="20%">
      <el-input v-model="chageLargeName" placeholder="请输入修改后的名称"></el-input>
      <span slot="footer">
      <el-button style="background-color:#303e9d;color: #eeeeee" @click="confirmLargeName">完 成</el-button></span>
    </el-dialog>
    <el-dialog :visible.sync="editPatrolSet" title="修改巡查信息" width="30%">
      <p>巡查项名称 <span style="color: #ce0e0f">*</span>
        <el-input v-model="pInfo.termName" size="small"></el-input>
      </p>
      <p style="margin-top: 10px">巡查项说明 <span style="color: #ce0e0f">*</span>
        <el-input v-model="pInfo.termDescribe" type="textarea"></el-input>
      </p>
      <span slot="footer">
<el-button style="background-color:#303e9d;color: #eeeeee" @click="submitEdit">确 定</el-button>
<el-button style="border: 1px solid #eee" @click="editPatrolSet=false">取 消</el-button>
      </span>
    </el-dialog>
    <patrol-set ref="setPatrol" @addStatus="receiveMessage"></patrol-set>
    <add-problem ref="addP" @addStatus="receiveMessage"></add-problem>
  </div>
</template>

<script>
import patrolSet from "../componentDialog/patrolSetting.vue";
import addProblem from "./addProblem.vue";

export default {
  name: "patrolSetting",
  components: {
    patrolSet,
    addProblem
  },
  data() {
    return {
      templateId: "",
      largeId: "",
      pInfo: {},
      collapse: true,
      cateTypeInfo: {},
      chageLargeName: "",
      activeCard: null,
      categoryTittle: null,
      largeType: 1,
      cateTypeList: [],
      largeName: "",
      templateName: "",
      score: "",
      loading: false,
      editPatrolSet: false,
      addCategory: false,
      CateName: false,
      searchFn: "",
      scoreTable: [
        {
          a: '卫生不达标',
          b: '2',
          c: '一般问题',
          d: '未关联',
        }
      ]
    }
  },
  created() {
    // this.fetchUser(this.$route.query)
  },
  watch: {
    '$route.query': {
      handler(newQuery) {
        this.fetchUser(newQuery)
      },
      immediate: true
    }
  },
  methods: {
    editPatrolSetting(val) {
      this.editPatrolSet = true
      // console.log(val)
      this.$api.patrolGetModifyTermDto({termId: val.termId}).then(res => {
        this.pInfo = res
      })
    },
    submitEdit() {
      const data = this.pInfo
      this.$api.patrolUpdateTermInfo(data).then(res => {
        if (res == 1) {
          this.$message.success("修改成功！")
          this.getCate(this.templateId)
          this.editPatrolSet = false
        }
      })
    },
    scrollToTarget(id) {
      const target = document.querySelector(`.target[data-id='${id}']`);
      target?.scrollIntoView({behavior: 'smooth', block: 'start'});
    },
    _setting() {
      this.$refs.setPatrol.handleOpen(this.templateId)
    },
    addPro(val) {
      this.$refs.addP.handleOpen(val)
    },
    fetchUser(val) {
      if (!val.templateId) return
      this.templateId = val.templateId
      this.templateName = val.templateName
      this.score = val.score
      this.getCate(val.templateId)
    },
    changeLargeType(key, keyWord) {
      this.largeType = key
    },
    getCate(id) {
      this.loading = true
      this.$api.patrolGetPatrolTemplateConfig({templateId: id}).then(res => {
        this.cateTypeInfo = res
        this.cateTypeList = res.largeVoList
        this.loading = false
      })
      // const loading = this.$loading({
      //   lock: true,
      //   text: 'Loading',
      //   spinner: 'el-icon-loading',
      //   background: 'rgba(255, 255, 255,0.5)'
      // });
      // setTimeout(() => {
      //   loading.close();
      // }, 1000);
    },
    comfirmCate() {
      const data = {
        templateId: this.templateId,
        largeName: this.largeName,
        largeType: this.largeType,
      }
      this.$api.patrolAddPatrolTemplateLarge(data).then(res => {
        if (res == 1) {
          this.$message.success("添加成功！")
          this.getCate(this.templateId)
          this.addCategory = false
          this.largeName = ""
          this.largeType = 1
        }
      })
    },
    goBack() {
      this.$router.back();
    },
    handleSelectionChange() {

    },
    addCate() {
      this.categoryTittle = '添加大类'
      this.addCategory = true
    },
    addInspection(a) {
      this.$router.push({
        path: '/addInspection',
        query: {
          largeId: a.largeId,
          largeProblemNum: a.largeProblemNum
        }
      })
    },
    editCateName(largeId) {
      this.CateName = true
      this.largeId = largeId
      this.chageLargeName = ""
    },
    deleteCateName(largeId) {
      this.$confirm('此操作将永久删除该巡查大类，是否继续？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const data = {
          largeId: largeId
        }
        this.$api.patrolDeleteLarge(data).then(res => {
          if (res == 1) {
            this.$message.success('删除成功')
            this.getCate(this.templateId)
          } else {
            this.$message.error('删除失败')
          }
        })
      })
    },
    receiveMessage(val) {
      if (val == 1) {
        this.getCate(this.templateId)
      }
    },
    confirmLargeName() {
      const data = {
        largeName: this.chageLargeName,
        largeId: this.largeId
      }
      this.$api.patrolUpdateLargeName(data).then(res => {
        if (res == 1) {
          this.$message.success("修改成功！")
          this.CateName = false
          this.getCate(this.templateId)
        }
      })
    },
    deletePro(val) {
      this.$confirm('此操作将永久删除该问题，是否继续？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const data = {
          problemId: val
        }
        this.$api.patrolDeleteProblem(data).then(res => {
          if (res == 1) {
            this.$message.success('删除成功')
            this.getCate(this.templateId)
          } else {
            this.$message.error('删除失败')
          }
        })
      })
    },
    deletePatorlInfo(val) {
      this.$confirm('此操作将永久删除该巡查项，是否继续？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const data = {
          termId: val
        }
        this.$api.patrolDeleteTerm(data).then(res => {
          if (res == 1) {
            this.$message.success('删除成功')
            this.getCate(this.templateId)
          } else {
            this.$message.error('删除失败')
          }
        })
      })
    },
    editPro(val) {
      this.$refs.addP.handleEdit(val)
    },
    searchM(val) {
      if (!val) this.cateTypeList=this.cateTypeInfo.largeVoList
      const filtered = this.filterByProblemKeyword(this.cateTypeList, val);
     this.cateTypeList=filtered
    },
    filterByProblemKeyword(data, keyword) {
      return data.reduce((acc, largeItem) => {
        // 过滤 termVoList 中的每一项
        const filteredTerms = largeItem.termVoList.reduce((termAcc, termItem) => {
          // 过滤问题项
          const matchedProblems = termItem.list.filter(problem =>
              problem.problemName.includes(keyword)
          );

          // 如果有匹配的 problem 才保留这个 term
          if (matchedProblems.length > 0) {
            termAcc.push({
              ...termItem,
              list: matchedProblems
            });
          }

          return termAcc;
        }, []);

        // 如果有匹配的 term 才保留这个 largeItem
        if (filteredTerms.length > 0) {
          acc.push({
            ...largeItem,
            termVoList: filteredTerms
          });
        }

        return acc;
      }, []);
    }
  }
}
</script>

<style scoped lang="less">
@import "../../../assets/css/public.css";

.scopePic {
  width: 80px;
  border: 1px solid #eeeeee;
  height: 30px;
  background-color: #eeeeee;
  line-height: 25px;
  text-align: center;
}

/deep/ .el-radio__input.is-checked + .el-radio__label {
  color: #303e9d;
}

/deep/ .el-radio__input.is-checked .el-radio__inner {
  color: #303e9d;
  background-color: #303e9d;
}

.tableCard {
  width: 100%;
  padding: 10px;
  margin-top: 15px;
  border: 1px solid #eee;
  box-sizing: border-box;

  .a {
    display: flex;
    align-items: center;
    justify-content: space-between;
  }
}


.el-button {
  background-color: #fff;
}

.centerBar {
  margin-top: 20px;
  width: 100%;
  display: flex;
  height: 100%;

  .left {
    width: 25%;
    padding: 15px;
    overflow: scroll;
    height: calc(100vh - 350px);
    border: 1px solid #eee;
  }

  .right {
    width: 75%;
    padding: 15px;
    height: calc(100vh - 350px);
    border: 1px solid #eee;
    overflow: scroll;
  }
}

.box-card {
  width: 100%;
  margin-top: 10px;
  box-sizing: border-box;
  justify-content: space-between;
  padding: 0 10px;
  display: flex;
  align-items: center;
  display: flex;
  border-radius: 5px;
  cursor: pointer;
  border: 1px solid transparent;
  cursor: pointer;
  position: relative;
  background-color: #eeeeee;
  transition: all 0.3s ease;
  min-height: 60px;
}

.box-card:hover {
  box-sizing: border-box;
  padding-bottom: 40px;
  min-height: 100px;
  background-color: #fff;
  border: 1px solid #303e9d;
}

.button-group {
  position: absolute;
  bottom: 5px;
  right: 40px;
  display: none;
  justify-content: center;
  gap: 10px;
  transition: opacity 0.3s;

  i {
    font-size: 18px;
    margin: 10px;
  }
}

.box-card:hover .button-group {
  display: flex;
}

.active-border {
  border: 1px solid #303e9d;
  background-color: #fff;
}

.topBar {
  width: 100%;
  height: 80px;
  border: 1px solid #eee;
  display: flex;
  justify-content: space-between;
  padding: 15px;
  box-sizing: border-box;

  .left {
    span {
      color: #ce0e0f;
    }
  }
}

</style>